<?php

namespace addons\Merchants\api\modules\v1\controllers;

use Yii;
use yii\web\UnprocessableEntityHttpException;
use api\controllers\UserAuthController;
use common\helpers\ResultHelper;
use common\helpers\AddonHelper;
use common\models\merchant\CommissionWithdraw;
use addons\Merchants\common\models\SettingForm;
use addons\Merchants\common\models\forms\CommissionWithdrawForm;

/**
 * 余额提现
 *
 * Class CommissionWithdrawController
 * @package addons\Merchants\api\modules\v1\controllers
 * @author YiiFrame <21931118@qq.com>
 */
class CommissionWithdrawController extends UserAuthController
{
    /**
     * @var CommissionWithdraw
     */
    public $modelClass = CommissionWithdraw::class;

    /**
     * 提现申请
     *
     * @return CommissionWithdraw|array|mixed|\yii\db\ActiveRecord
     * @throws UnprocessableEntityHttpException
     */
    public function actionCreate()
    {
        // 开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $config = new SettingForm();
            $config->attributes = AddonHelper::getBackendConfig();

            $model = new CommissionWithdrawForm();
            $model->attributes = Yii::$app->request->post();
            $model->merchant_id = Yii::$app->user->identity->merchant_id;
            $model->merchant = Yii::$app->services->merchant->findById($model->merchant_id);
            $model->config = $config;

            if (!$model->validate()) {
                return ResultHelper::json(422, $this->getError($model));
            }

            if (!$model->save()) {
                return ResultHelper::json(422, $this->getError($model));
            }

            $transaction->commit();

            return $model;
        } catch (\Exception $e) {
            $transaction->rollBack();

            return ResultHelper::json(422, $e->getMessage());
        }
    }

    /**
     * 配置
     *
     * @return array
     */
    public function actionConfig()
    {
        // 判断是否开启提现申请
        $setting = new SettingForm();
        $setting->attributes = AddonHelper::getBackendConfig();

        $defaultBankAccount = Yii::$app->services->merchantBankAccount->findDefault();
        if ($defaultBankAccount && !in_array($defaultBankAccount['account_type'], $setting->withdraw_account)) {
            $defaultBankAccount = [];
        }

        return [
            'withdraw_is_open' => $setting->withdraw_is_open,
            'withdraw_account' => $setting->withdraw_account,
            'withdraw_lowest_money' => $setting->withdraw_lowest_money,
            'account' => Yii::$app->services->merchantAccount->findIdentity(),
            'defaultBankAccount' => $defaultBankAccount
        ];
    }
}